package com.weixin.base.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.weixin.base.service.AdminReplyService;
import com.weixin.base.service.MessageService;
import com.weixin.base.service.ReplyService;
import com.weixin.base.util.ExtJsPageHelper;
import com.weixin.base.util.ListRange;
import com.weixin.base.util.PropertiesFile;
import com.weixin.base.util.Tools;
import com.weixin.entity.TbWxMessage;

@Controller
public class AdminReplyAction {

	@Autowired
	private AdminReplyService adminReplyService;

	@Autowired
	private PropertiesFile propertiesFile;

	/**
	 * 查询用户所有跳转链接
	 */
	@RequestMapping(value = "/module/main/selectAdminUserUrl.do")
	public void selectAdminUserUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Map<String, Object>> splist = adminReplyService.selectUserUrl(Tools.convertRi(request.getParameter("userid")));
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(splist);
		response.getWriter().print(result);
	}
	
	/**
	 * 查询用户所有跳转链接
	 */
	@RequestMapping(value = "/module/main/selectAdminUserKeys.do")
	public void selectAdminUserKeys(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Map<String, Object>> splist = adminReplyService.selectUserKeys(Tools.convertRi(request.getParameter("userid")));
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(splist);
		response.getWriter().print(result);
	}
	
	/**
	 * 查询所有用户
	 */
	@RequestMapping(value = "/module/main/selectAdminUsers.do")
	public void selectAdminUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Map<String, Object>> splist = adminReplyService.selectAdminUsers();
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(splist);
		response.getWriter().print(result);
	}

	/**
	 * 添加关注消息记录
	 */
	@RequestMapping(value = "/module/main/saveAdminReplyNotice.do")
	public void saveAdminReplyNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		String picUrl = "";
		/**
		 * result 返回值：1.成功 2.失败 3.图片格式不正确（仅支持JPG、PNG）
		 */
		int result = 2;

		TbWxMessage tbWxMessage = new TbWxMessage();
		tbWxMessage.setDCreateTime(new Date());
		tbWxMessage.setNReplyType(1);
		tbWxMessage.setNtype(6);
		tbWxMessage.setNUserId(Tools.convertRi(request.getParameter("userid")));
		tbWxMessage.setSDescription(Tools.convertRs(request.getParameter("sDescription")));
		tbWxMessage.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxMessage.setSTitle(Tools.convertRs(request.getParameter("sTitle")));
		tbWxMessage.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxMessage.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxMessage.setNKey(0);
		
		if(tbWxMessage.getNUserId()<=0){
			result = 4;
			response.getWriter().print("{save:'true',success:'" + result + "'}");
			return;
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("txtpath");

		if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
			String filenameold = file.getOriginalFilename();
			String hz = filenameold.substring(filenameold.lastIndexOf(".", filenameold.length()), filenameold.length());

			if (hz.equalsIgnoreCase(".JPG") || hz.equalsIgnoreCase(".PNG")) {

				String newfilename = Tools.radomName(2) + hz;
				InputStream input = file.getInputStream();

				String folderPath = propertiesFile.getImagefolderPath() + tbWxMessage.getNUserId() + "\\";
				if (Tools.upload(newfilename, input, folderPath)) {
					picUrl = propertiesFile.getImageUrlPath() + tbWxMessage.getNUserId() + "/" + newfilename;
				}

			} else {
				result = 3;
				response.getWriter().print("{save:'true',success:'" + result + "'}");
				return;
			}
		}

		tbWxMessage.setSPicUrl(picUrl);
		result = adminReplyService.saveReplyNotice(tbWxMessage);

		// uploadTemplate(request, radomName());

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 查询关注消息 nReplyType：消息回复类型（1.关注回复 2自动回复 3自定义菜单回复 4关键字回复）
	 * 
	 * ntype：消息类型（1.文本 2图片 3语音 4视频 5 音乐 6图文）
	 */
	@RequestMapping(value = "/module/main/searchAdminReplyNotice.do")
	public void searchAdminReplyNotice(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		int userid = Tools.convertRi(request.getParameter("userid"));
		int nReplyType = 1;
		int ntype = 6;
		Page page = adminReplyService.searchReplyNotice(pr, userid, nReplyType, ntype);
		List tblist = (List) page.getResult();
		ListRange resultList = new ListRange();
		resultList.setList(tblist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		String result = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(resultList);
		response.getWriter().print(result);
	}

	/**
	 * 修改关注消息记录
	 */
	@RequestMapping(value = "/module/main/updateAdminReplyNotice.do")
	public void updateAdminReplyNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		/**
		 * result 返回值：1.成功 2.失败 3.图片格式不正确（仅支持JPG、PNG）
		 */
		int result = 2;
		/**
		 * picUrl :标识图片是否改变 值为1不改变 其余表示改变
		 */
		String picUrl = Tools.convertRs(request.getParameter("spicUrl"));

		TbWxMessage tbWxMessage = new TbWxMessage();
		tbWxMessage.setSDescription(Tools.convertRs(request.getParameter("sDescription")));
		tbWxMessage.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxMessage.setSTitle(Tools.convertRs(request.getParameter("sTitle")));
		tbWxMessage.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxMessage.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxMessage.setNKey(Tools.convertRi(request.getParameter("nkey")));
		tbWxMessage.setNWxMessageId(Tools.convertRi(request.getParameter("nwxMessageId")));

		if (!picUrl.equals("1")) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("txtpath");

			if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
				String filenameold = file.getOriginalFilename();
				String hz = filenameold.substring(filenameold.lastIndexOf(".", filenameold.length()), filenameold.length());

				if (hz.equalsIgnoreCase(".JPG") || hz.equalsIgnoreCase(".PNG")) {

					String newfilename = Tools.radomName(2) + hz;
					InputStream input = file.getInputStream();

					String folderPath = propertiesFile.getImagefolderPath() + tbWxMessage.getNUserId() + "\\";
					if (Tools.upload(newfilename, input, folderPath)) {
						picUrl = propertiesFile.getImageUrlPath() + tbWxMessage.getNUserId() + "/" + newfilename;
					}

				} else {
					result = 3;
					response.getWriter().print("{save:'true',success:'" + result + "'}");
					return;
				}
			}
		}

		tbWxMessage.setSPicUrl(picUrl);
		result = adminReplyService.updateReplyNotice(tbWxMessage);

		// uploadTemplate(request, radomName());

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 消息删除
	 */
	@RequestMapping(value = "/module/main/delAdminReplyNotice.do")
	public void delAdminReplyNotice(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int nWxMessageId = Tools.convertRi(request.getParameter("ids"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminReplyService.delReplyNotice(nWxMessageId);
		response.getWriter().print(result);
	}

	/**
	 * 添加自动消息记录 nReplyType：消息回复类型（1.关注回复 2自动回复） ntype：消息类型（1.文本 2图片 3语音 4视频 5 音乐
	 * 6图文）
	 */
	@RequestMapping(value = "/module/main/saveAdminReplyAuto.do")
	public void saveAdminReplyAuto(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		String picUrl = "";
		/**
		 * result 返回值：1.成功 2.失败 3.图片格式不正确（仅支持JPG、PNG）
		 */
		int result = 2;

		TbWxMessage tbWxMessage = new TbWxMessage();
		tbWxMessage.setDCreateTime(new Date());
		tbWxMessage.setNReplyType(2);
		tbWxMessage.setNtype(6);
		tbWxMessage.setNUserId(Tools.convertRi(request.getParameter("userid")));
		tbWxMessage.setSDescription(Tools.convertRs(request.getParameter("sDescription")));
		tbWxMessage.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxMessage.setSTitle(Tools.convertRs(request.getParameter("sTitle")));
		tbWxMessage.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxMessage.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxMessage.setNKey(0);
		
		if(tbWxMessage.getNUserId()<=0){
			result = 4;
			response.getWriter().print("{save:'true',success:'" + result + "'}");
			return;
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("txtpath");

		if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
			String filenameold = file.getOriginalFilename();
			String hz = filenameold.substring(filenameold.lastIndexOf(".", filenameold.length()), filenameold.length());

			if (hz.equalsIgnoreCase(".JPG") || hz.equalsIgnoreCase(".PNG")) {

				String newfilename = Tools.radomName(2) + hz;
				InputStream input = file.getInputStream();

				String folderPath = propertiesFile.getImagefolderPath() + tbWxMessage.getNUserId() + "\\";
				if (Tools.upload(newfilename, input, folderPath)) {
					picUrl = propertiesFile.getImageUrlPath() + tbWxMessage.getNUserId() + "/" + newfilename;
				}

			} else {
				result = 3;
				response.getWriter().print("{save:'true',success:'" + result + "'}");
				return;
			}
		}

		tbWxMessage.setSPicUrl(picUrl);
		result = adminReplyService.saveReplyNotice(tbWxMessage);

		// uploadTemplate(request, radomName());

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 查询自动消息 nReplyType：消息回复类型（1.关注回复 2自动回复 3自定义菜单回复 4关键字回复）
	 * 
	 * ntype：消息类型（1.文本 2图片 3语音 4视频 5 音乐 6图文）
	 */
	@RequestMapping(value = "/module/main/searchAdminReplyAuto.do")
	public void searchAdminReplyAuto(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		int userid = Tools.convertRi(request.getParameter("userid"));
		int nReplyType = 2;
		int ntype = 6;
		Page page = adminReplyService.searchReplyNotice(pr, userid, nReplyType, ntype);
		List tblist = (List) page.getResult();
		ListRange resultList = new ListRange();
		resultList.setList(tblist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		String result = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(resultList);
		response.getWriter().print(result);
	}
	
	/**
	 * 查询自动消息 nReplyType：消息回复类型（1关注回复2自动回复3自定义菜单回复 4关键字回复）
	 * 
	 * ntype：消息类型（1.文本 2图片 3语音 4视频 5 音乐 6图文）
	 */
	@RequestMapping(value = "/module/main/searchAdminReplyCustomMenu.do")
	public void searchAdminReplyCustomMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		int userid = Tools.convertRi(request.getParameter("userid"));
		int nReplyType = 3;
		int ntype = 6;
		Page page = adminReplyService.searchReplyNotice(pr, userid, nReplyType, ntype);
		List tblist = (List) page.getResult();
		ListRange resultList = new ListRange();
		resultList.setList(tblist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		String result = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(resultList);
		response.getWriter().print(result);
	}
	
	/**
	 * 添加自动消息记录 nReplyType：消息回复类型（1关注回复2自动回复3自定义菜单回复 4关键字回复） ntype：消息类型（1.文本 2图片 3语音 4视频 5 音乐
	 * 6图文）
	 */
	@RequestMapping(value = "/module/main/saveAdminReplyCustomMenu.do")
	public void saveAdminReplyCustomMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		String picUrl = "";
		/**
		 * result 返回值：1.成功 2.失败 3.图片格式不正确（仅支持JPG、PNG）
		 */
		int result = 2;

		TbWxMessage tbWxMessage = new TbWxMessage();
		tbWxMessage.setDCreateTime(new Date());
		tbWxMessage.setNReplyType(3);
		tbWxMessage.setNtype(6);
		tbWxMessage.setNUserId(Tools.convertRi(request.getParameter("userid")));
		tbWxMessage.setSDescription(Tools.convertRs(request.getParameter("sDescription")));
		tbWxMessage.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxMessage.setSTitle(Tools.convertRs(request.getParameter("sTitle")));
		tbWxMessage.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxMessage.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxMessage.setNKey(Tools.convertRi(request.getParameter("nkey")));

		if(tbWxMessage.getNUserId()<=0){
			result = 4;
			response.getWriter().print("{save:'true',success:'" + result + "'}");
			return;
		}
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("txtpath");

		if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
			String filenameold = file.getOriginalFilename();
			String hz = filenameold.substring(filenameold.lastIndexOf(".", filenameold.length()), filenameold.length());

			if (hz.equalsIgnoreCase(".JPG") || hz.equalsIgnoreCase(".PNG")) {

				String newfilename = Tools.radomName(2) + hz;
				InputStream input = file.getInputStream();

				String folderPath = propertiesFile.getImagefolderPath() + tbWxMessage.getNUserId() + "\\";
				if (Tools.upload(newfilename, input, folderPath)) {
					picUrl = propertiesFile.getImageUrlPath() + tbWxMessage.getNUserId() + "/" + newfilename;
				}

			} else {
				result = 3;
				response.getWriter().print("{save:'true',success:'" + result + "'}");
				return;
			}
		}

		tbWxMessage.setSPicUrl(picUrl);
		result = adminReplyService.saveReplyNotice(tbWxMessage);

		// uploadTemplate(request, radomName());

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

}